"""
日志模块，提供日志记录和历史追踪功能
"""

import os
import json
import logging
import datetime
from typing import Dict, Any, Optional, List

class AgentLogger:
    """
    代理日志记录器，用于记录代理活动和历史
    """
    
    def __init__(self, config: Dict[str, Any]):
        """
        初始化日志记录器
        
        参数:
            config: 日志配置
        """
        self.config = config
        self.level = getattr(logging, config.get("level", "INFO"))
        self.save_history = config.get("save_history", True)
        self.history_path = config.get("history_path", "./history")
        
        # 设置基本日志
        logging.basicConfig(
            level=self.level,
            format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
            datefmt='%Y-%m-%d %H:%M:%S'
        )
        
        self.logger = logging.getLogger("WebSearchAgent")
        
        # 会话记录
        self.session_id = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
        self.history = []
        
        # 创建历史目录
        if self.save_history and not os.path.exists(self.history_path):
            os.makedirs(self.history_path)
            
        self.logger.info(f"日志系统初始化，会话ID: {self.session_id}")
        
    def log(self, level: str, message: str, data: Optional[Dict[str, Any]] = None):
        """
        记录日志
        
        参数:
            level: 日志级别
            message: 日志消息
            data: 附加数据
        """
        log_method = getattr(self.logger, level.lower(), self.logger.info)
        log_method(message)
        
        # 记录到历史
        entry = {
            "timestamp": datetime.datetime.now().isoformat(),
            "level": level,
            "message": message
        }
        
        if data:
            entry["data"] = data
            
        self.history.append(entry)
        
    def info(self, message: str, data: Optional[Dict[str, Any]] = None):
        """记录信息级别日志"""
        self.log("INFO", message, data)
        
    def warning(self, message: str, data: Optional[Dict[str, Any]] = None):
        """记录警告级别日志"""
        self.log("WARNING", message, data)
        
    def error(self, message: str, data: Optional[Dict[str, Any]] = None):
        """记录错误级别日志"""
        self.log("ERROR", message, data)
        
    def debug(self, message: str, data: Optional[Dict[str, Any]] = None):
        """记录调试级别日志"""
        self.log("DEBUG", message, data)
        
    def log_search(self, query: str, results: List[Dict[str, Any]]):
        """
        记录搜索操作
        
        参数:
            query: 搜索关键词
            results: 搜索结果
        """
        self.info(f"执行搜索: {query}", {
            "action": "search",
            "query": query,
            "results_count": len(results)
        })
        
    def log_decision(self, decision: Dict[str, Any]):
        """
        记录决策操作
        
        参数:
            decision: 决策信息
        """
        self.info(f"做出决策: {decision.get('action')}", {
            "action": "decide",
            "decision": decision
        })
        
    def log_answer(self, question: str, answer: str):
        """
        记录回答操作
        
        参数:
            question: 问题
            answer: 回答
        """
        self.info(f"生成回答: {question[:30]}...", {
            "action": "answer",
            "question": question,
            "answer_length": len(answer)
        })
        
    def save(self):
        """
        保存历史记录到文件
        """
        if not self.save_history:
            return
            
        file_path = os.path.join(self.history_path, f"session_{self.session_id}.json")
        with open(file_path, "w", encoding="utf-8") as f:
            json.dump({
                "session_id": self.session_id,
                "start_time": self.history[0]["timestamp"] if self.history else None,
                "end_time": datetime.datetime.now().isoformat(),
                "history": self.history
            }, f, ensure_ascii=False, indent=2)
            
        self.logger.info(f"历史记录已保存到 {file_path}")
        
    def get_history(self):
        """
        获取历史记录
        
        返回:
            历史记录列表
        """
        return self.history 